import { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import classNames from 'classnames'
import {
  todoCheckAll,
  todoDel,
  todoModifyStatus,
} from '../../store/actions/todo'

export default function TodoMain() {
  const dispatch = useDispatch()
  const list = useSelector((state) => state.todo)
  const handleDel = (id) => dispatch(todoDel(id))
  const handleChange = (id) => dispatch(todoModifyStatus(id))
  // 由于点击全选，要在当前状态的基础上进行取反，所以呀，要先拿到当前状态
  const nowStatus = list.every((item) => item.done)
  const handleCheckAllChange = () => dispatch(todoCheckAll(!nowStatus))
  // !#1 准备变量
  const [currentId, setCurrentId] = useState('')
  // !#3 一旦进行了双击，currentId 是不是就变成了你当前双击的那一项的 id 了呀
  const handleDblClick = (id) => setCurrentId(id)
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={nowStatus}
        onChange={handleCheckAllChange}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {list.map((item) => (
          <li
            key={item.id}
            className={classNames({
              completed: item.done,
              // !#4 用 currentId 和 item.id 进行比较，true 就应用 editing class
              editing: item.id === currentId,
            })}
          >
            <div className='view'>
              <input
                className='toggle'
                type='checkbox'
                checked={item.done}
                onChange={() => handleChange(item.id)}
              />
              {/* //!#2 绑定双击事件并传递 id */}
              <label onDoubleClick={() => handleDblClick(item.id)}>
                {item.name}
              </label>
              <button
                className='destroy'
                onClick={() => handleDel(item.id)}
              ></button>
            </div>
            <input className='edit' value='Create a TodoMVC template' />
          </li>
        ))}
      </ul>
    </section>
  )
}
